/* ========================================================

    目录结构：
    - src
        + assets      -> 放静态资源，例如图片
        + components  -> 公共组件
        + data        -> 数据文件
        - routers     -> 路由栈
            + All
            + Mine
            + Home
            - Music
                + components   -> 私有组件
                + container
                + store
                index.js
            index.js   -> 在这里注册navigator，注册过的组件，其props会增加navigation属性
        + service  -> 服务目录
        App.js     -> 项目入口
        Config.js  -> 全局store

   ====================================================== */

import React, { Component } from 'react'
import { Alert, Platform, ToastAndroid, BackHandler, Linking, AsyncStorage,PushNotificationIOS} from 'react-native'
import { observer, Provider } from 'mobx-react'
import SplashScreen from 'rn-splash-screen'
import Stores from './Store'
import Routers from './routers'
import { enableLogging } from 'mobx-logger'
import navigationhelper from './components/navigationhelper'
import AuthVerSion from './service/Auth'
import DeviceInfo from 'react-native-device-info';
import XGPush from 'react-native-xinge-push';
import Storage from "react-native-storage";
import StorageDatas from './utils/storageDatas'
import * as WeChat from 'react-native-wechat';
import md5 from "react-native-md5";
import CodePush from 'react-native-code-push' 


const AndroidKey = "dTnVugYqp-Q7Ig57iNPVutqXCw-F1dc7b5c8-d157-4381-b67f-89ee0e28c51b"
const ioSKey = "hzJGVPdAJcdtk6_Un9DVQfdE3sxf1dc7b5c8-d157-4381-b67f-89ee0e28c51b"


const storage = new Storage({
    // 最大容量，默认值1000条数据循环存储
    size: 3000,
    // 存储引擎：对于RN使用AsyncStorage，对于web使用window.localStorage
    // 如果不指定则数据只会保存在内存中，重启后即丢失
    storageBackend: AsyncStorage,
    // 数据过期时间，默认一整天（1000 * 3600 * 24 毫秒），设为null则永不过期
    defaultExpires: 1000 * 3600 * 24,
    // 读写时在内存中缓存数据。默认启用。
    enableCache: true,
    // 如果storage中没有相应数据，或数据已过期，
    // 则会调用相应的sync方法，无缝返回最新数据。
    // sync方法的具体说明会在后文提到
    // 你可以在构造函数这里就写好sync的方法
    // 或是写到另一个文件里，这里require引入
    // 或是在任何时候，直接对storage.sync进行赋值修改
    sync: null  // 这个sync文件是要你自己写的
})
global.storage = storage;

if (__DEV__) {
    enableLogging({
        predicate: () => __DEV__ && Boolean(window.navigator.userAgent),
        action: true,
        reaction: true,
        transaction: true,
        compute: true,
    });
}

@observer



export default class App extends Component<{}> {
    constructor(props) {
        super(props);
        this.account = ''
        this.index = 0
        this.initGPush()
    }
    componentWillMount() {
        this.checkVersionUpdate()
        this.getPhoneInfo()
    }

    checkVersionUpdate=()=>{
        let key;
        if (Platform.OS === 'android') {
            key = AndroidKey
        } else {
            key = ioSKey
        }
        CodePush.sync({
            deploymentKey:key,
            updateDialog:false,
            installMode:CodePush.InstallMode.IMMEDIATE
        });
    }

    getPhoneInfo =()=>{
        AuthVerSion.getPhoneInfo({
            system: DeviceInfo.getSystemName(),
            appVersion: DeviceInfo.getVersion(),
            version: DeviceInfo.getSystemVersion(),
            phone_model: DeviceInfo.getModel(),
            uuuid: DeviceInfo.getUniqueID()
        }).then((res) => {
            if (res.status == 'success') {
                if (res.data.version.newest == 1) {
                    Alert.alert('提示', '检查到新版本,是否更新?', [
                        {
                            text: '是', onPress: () => {
                                Linking.openURL(res.data.version.download_url).catch(err => Layer.showMsg('跳转失败'));
                            }
                        },
                        { text: '否', onPress: () => { } },
                    ])
                }
            }

        }).catch((error) => {
            Layer.showMsg(error.message)
        })
    }
    initGPush = () => {
    //    console.log('设备====1',DeviceInfo.getSystemName());
    //    console.log('设备====2',DeviceInfo.getVersion());
    //    console.log('设备====3',DeviceInfo.getSystemVersion());
       let hex_md5v = md5.hex_md5(DeviceInfo.getUniqueID());
        // 初始化
        if (Platform.OS === 'android') {
            // 请将YOUR_ACCESS_KEY修改为APP的AccessKey
            XGPush.init(2100341586, 'A44GTVHV745W');
        } else {
            // 请将YOUR_ACCESS_KEY修改为APP的AccessKey
            XGPush.init(2200341587, 'IXV28U47E1SZ');
        }

        // PushNotificationIOS.addEventListener('register', (token) => {

        //  console.log('token===',token)
          
        //   });
          
        //  PushNotificationIOS.requestPermissions();

        XGPush.setHuaweiDebug(true);
        // 小米
        XGPush.initXiaomi('2882303761518137600', '5321813779600');

        // 魅族
        XGPush.initMeizu('1007487', 'af283b3e39a44367a8b080364171a1fd');

        // 华为请到 build.gradle manifestPlaceholders 配置
        // 第三方推送开关（华为、小米、魅族）
        XGPush.enableOtherPush(true);
        XGPush.addEventListener('message', this._onMessage);
        XGPush.addEventListener('notification', this._onNotification);
        XGPush.register(hex_md5v).then(result => {

        }).catch(err => {
        });
    }

    _onMessage(message) {
        XGPush.getApplicationIconBadgeNumber((number) => alert(number));
        alert('收到消息: ' + message.content);
    }

    _onNotification(notification) {
        const key = 'userAccount';
        StorageDatas.loadLocalStorage(key).then(data => {
            // console.log('=======>>>>', data)
            if (data.userAccount) {
                if (notification.clicked === true) {
                    Alert.alert(
                        notification.aps.alert.title,
                        notification.aps.alert.body,
                        [
                            { text: '好', onPress: () => console.log('确定') },
                        ])
                } else {
                    Alert.alert(
                        notification.aps.alert.title,
                        notification.aps.alert.body,
                        [
                            { text: '好', onPress: () => console.log('确定') },
                        ])
                }
            }
        }).catch(err => {
            // navigationhelper.push('Login')
        });

    }

    componentWillUnmount() {
        XGPush.removeEventListener('message', this._onMessage);
        XGPush.removeEventListener('notification', this._onNotification);
    }

    componentDidMount() {
        console.reportErrorsAsExceptions = false
        // WeChat.registerApp('wx613aae94beba7c40');
        setTimeout(() => {
            SplashScreen.hide()
            if (Platform.OS === 'android') {
                BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid)
            }
        }, 500)
    }
    componentWillUnmount() {
        if (Platform.OS === 'android') {
            BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid)
        }
    }
    onBackAndroid = () => {
        if (this.index == 0) {
            if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
                return false
            }
            this.lastBackPressed = Date.now()
            ToastAndroid.show('再点击一次退出应用', ToastAndroid.SHORT)
            return true
        }

    }
    onNavigationStateChange = (nav) => {
        this.index = nav.index
    }

    setNavigator = (ref) => {
        navigationhelper.setTopLevelNavigator(ref)
    }

    render() {
        const { ...storesArray } = Stores
        return (
            <Provider {...storesArray}>
                <Routers
                    ref={this.setNavigator}
                    onNavigationStateChange={this.onNavigationStateChange}
                    screenProps={{ themeColor: 'white' }}
                />
            </Provider>
        )
    }
}


console.disableYellowBox = true